package cn.iocoder.yudao.module.member.service.deliverypersoninfo;

import cn.iocoder.yudao.framework.common.util.CollectionUtil;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.role.UserRoleApi;
import cn.iocoder.yudao.module.system.api.role.dto.UserRoleDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.member.controller.admin.deliverypersoninfo.vo.*;
import cn.iocoder.yudao.module.member.dal.dataobject.deliverypersoninfo.DeliveryPersonInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.member.dal.mysql.deliverypersoninfo.DeliveryPersonInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

/**
 * 配送员信息扩展 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DeliveryPersonInfoServiceImpl implements DeliveryPersonInfoService {

    @Resource
    private DeliveryPersonInfoMapper deliveryPersonInfoMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private UserRoleApi userRoleApi;

    @Resource
    private DeptApi deptApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createDeliveryPersonInfo(DeliveryPersonInfoSaveReqVO createReqVO) {

        AdminUserRespDTO dto = new AdminUserRespDTO();
        // 默认密码 888888
        dto.setUsername(createReqVO.getCode());
        dto.setNickname(createReqVO.getName());
        dto.setPassword("888888");
        dto.setDeptId(createReqVO.getDeptId());
        dto.setPostIds(createReqVO.getPostIds());
        dto.setMobile(createReqVO.getMobile());
        dto.setStatus(0);
        dto.setAvatar(createReqVO.getAvatar());
        dto.setRemark(createReqVO.getRemark());
        dto.setSex(createReqVO.getGender());
        dto.setType(1);
        Long aLong = adminUserApi.insertUser(dto);

        // 存入权限关系表
        if (!CollectionUtil.isEmpty(createReqVO.getRoleId())){
            createReqVO.getRoleId().forEach(
                    x -> {
                        userRoleApi.insertUserRole(new UserRoleDTO().setUserId(aLong).setRoleId(x));
                    }
            );
        }


        // 插入
        DeliveryPersonInfoDO deliveryPersonInfo = BeanUtils.toBean(createReqVO, DeliveryPersonInfoDO.class);
        deliveryPersonInfo.setCode(createReqVO.getCode());
        deliveryPersonInfo.setSystemUserId(aLong);
        deliveryPersonInfoMapper.insert(deliveryPersonInfo);
        // 返回
        return deliveryPersonInfo.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeliveryPersonInfo(DeliveryPersonInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateDeliveryPersonInfoExists(updateReqVO.getId());

        AdminUserRespDTO respDTO = new AdminUserRespDTO();
        respDTO.setId(updateReqVO.getSystemUserId());
        respDTO.setSex(updateReqVO.getGender());
        respDTO.setMobile(updateReqVO.getMobile());
        respDTO.setRemark(updateReqVO.getRemark());
        respDTO.setDeptId(updateReqVO.getDeptId());
        respDTO.setPostIds(CollectionUtil.isEmpty(updateReqVO.getPostIds()) ? null : updateReqVO.getPostIds());
        respDTO.setAvatar(updateReqVO.getAvatar());
        adminUserApi.updateUser(respDTO);

        // 更新权限
        if (!CollectionUtil.isEmpty(updateReqVO.getRoleId())){
            updateReqVO.getRoleId().forEach(
                    x -> {
                        userRoleApi.updateUserRole(new UserRoleDTO().setUserId(updateReqVO.getSystemUserId()).setRoleId(x));
                    }
            );
        }

        // 更新
        DeliveryPersonInfoDO updateObj = BeanUtils.toBean(updateReqVO, DeliveryPersonInfoDO.class);
        deliveryPersonInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeliveryPersonInfo(Long id) {
        // 校验存在
        validateDeliveryPersonInfoExists(id);
        // 删除
        deliveryPersonInfoMapper.deleteById(id);
    }

    private void validateDeliveryPersonInfoExists(Long id) {
        if (deliveryPersonInfoMapper.selectById(id) == null) {
            throw exception(DELIVERY_PERSON_INFO_NOT_EXISTS);
        }
    }

    @Override
    public DeliveryPersonInfoDO getDeliveryPersonInfo(Long id) {

        DeliveryPersonInfoDO deliveryPersonInfoDO = deliveryPersonInfoMapper.selectById(id);
        deliveryPersonInfoDO.setRoleId(userRoleApi.selectUserRole(deliveryPersonInfoDO.getSystemUserId()).stream().map(UserRoleDTO::getRoleId).collect(Collectors.toList()));
        return deliveryPersonInfoDO;
    }

    @Override
    public PageResult<DeliveryPersonInfoDO> getDeliveryPersonInfoPage(DeliveryPersonInfoPageReqVO pageReqVO) {
        PageResult<DeliveryPersonInfoDO> pageResult = deliveryPersonInfoMapper.selectPage(pageReqVO);
        pageResult.getList().forEach(x -> {
            x.setDeptName(deptApi.getDept(x.getDeptId()).getName());
        });
        return pageResult;
    }

}